/* =============================================================
 * h5_carge_select.js v1.1.0
 * =============================================================
 * Original written by Ysy
 * =============================================================
 * Date 27/05/2020
 * ============================================================ */


(function (factory) {
    "use strict";
    if (typeof define === 'function' && define.amd) {
        define(['jquery'], factory);
    } else {
        factory(jQuery);
    }
}(function ($) {

    let CargoSelect = function (element, options) {
        this.options = $.extend({}, $.fn.cargoSelect.defaults, options);
        this.$element = $(element);
        this.$main = $(this.options.main);
        this.$header = $(this.options.header);
        this.$search = $(this.options.search);
        this.$items = $(this.options.items);
        this.afterSelect = this.options.afterSelect;
        this.source = this.options.source;
        this.pageNo = 1;
        this.pageSize = 100;
        this.shown = true;
        this.appendFlag = false;
        this.data = [];
        this.searchData = [];
        this.searchFlag = false;
        this.listen();
    };

    CargoSelect.prototype = {

        constructor: CargoSelect,

        render: function () {// 渲染
            // header
            this.$main.append(this.$header);
            // 查询框
            this.$main.append(this.$search);
            // 数据列表
            this.$main.append(this.$items);
            $("body").append(this.$main);

            // 加载文本或数据
            if ($.isFunction(this.source)) {
                this.source($.proxy(this.process, this));
            } else if (this.source) {
                this.data = this.source;
                this.displayText();
            }
        },

        pagination: function (pageNo, pageSize, array) {
            let index = (pageNo - 1) * pageSize;
            return (index + pageSize >= array.length) ? array.slice(index, array.length) : array.slice(index, index + pageSize);
        },

        show: function () {
            $("body").find(this.$main).toggleClass("cargo_toggle");
        },

        hide: function () {
            $("body").find(this.$main).toggleClass("cargo_toggle");
            // 清空查询框
            this.$search.find("input").val("");
            this.shown = true;
            this.appendFlag = false;
            this.searchFlag = false;
            this.data = [];
            this.searchData = [];
            this.destroy();
        },

        listen: function () {
            this.$element
                .on("click", $.proxy(this.init, this));

            this.$header
                .on("click", "svg", $.proxy(this.hide, this));

            this.$search
                .on("input", "input", $.proxy(this.input, this));

            this.$items
                .on("click", ".item", $.proxy(this.select, this))
                .on("scroll", $.proxy(this.scroll, this));
        },

        scroll: function () {
            let scrollTop = this.$items[0].scrollTop,
                clientHeight = this.$items[0].clientHeight,
                scrollHeight = this.$items[0].scrollHeight;

            // 距离底部30px时触发
            if (scrollHeight - (scrollTop + clientHeight) < 30) {
                this.pageNo++;
                this.shown = false;
                this.appendFlag = true;
                this.displayText();
            }
        },

        isEmptyStr: function (str) {
            let boolean = true;

            // 正则表达式用于判断字符串是否全部由空格或换行符组成
            let reg = /^\s*$/;
            if (str && str !== undefined && str != null && str !== "" && !reg.test(str)) boolean = false;

            return boolean;
        },

        input: function (e) {
            let input = $(e.target).val();
            this.shown = false;
            this.searchData = [];

            if (this.isEmptyStr(input)) {
                this.searchFlag = false;
                this.appendFlag = false;
                this.displayText();
                return false;
            }

            $.each(this.data, (index, value) => {
                if (value.goodsName.indexOf(input) !== -1)
                    this.searchData.push(value);
            });

            this.searchFlag = true;
            this.appendFlag = false;
            // 重置分页
            this.pageNo = 1;
            this.displayText();
        },

        displayText: function () {// 显示文本或数据
            let html = "";
            let data = this.searchFlag ? this.searchData : this.data;
            let list = this.pagination(this.pageNo, this.pageSize, data);

            $.each(list, (index, value) => {
                html += "<div class='item'>";
                html += "<div data-goodsid='" + value.goodsId + "' data-goodstypeid='" + value.goodsTypeId + "' data-goodstypename='" + value.goodsTypeName + "'>" + value.goodsName + "</div>";
                html += "</div>";
            });
            if (this.appendFlag) {
                this.$items.append(html);
            } else {
                this.$items.html(html);
            }

            // 显示动态效果
            if (this.shown) this.show();
        },

        init: function () {
            this.render();
        },

        select: function (e) {
            let ele = $(e.target).closest(".item").find("div");
            let goodsId = $(ele).data("goodsid");
            let goodsName = $(ele).text();
            let goodsTypeId = $(ele).data("goodstypeid");
            let goodsTypeName = $(ele).data("goodstypename");
            this.$element.val(goodsName);
            this.$element.data("goodsId", goodsId);
            this.$element.data("goodsTypeId", goodsTypeId);
            this.$element.data("goodsTypeName", goodsTypeName);
            this.hide();
            this.afterSelect(goodsId, goodsName, goodsTypeId, goodsTypeName);
        },

        process: function (data) {
            this.data = data;
            this.displayText(data);
        },

        destroy: function () {
            setTimeout(() => {
                this.$main.detach();
            }, 300);
        },
    };

    let old = $.fn.cargoSelect;

    $.fn.cargoSelect = function (options) {
        return new CargoSelect(this, options);
    };

    $.fn.cargoSelect.defaults = {
        main: "<div class='cargo_select'></div>",
        header: "<div class='header'>" +
            "       <svg class='icon svg-icon' aria-hidden='true'>" +
            "           <use xlink:href='#iconright'></use>" +
            "       </svg>" +
            "       <span class='middle'>选择货物</span>" +
            "       <span class='right'></span>" +
            "   </div>",
        search: "<div class='search'>" +
            "        <div class='search_wrap'>" +
            "            <svg class='icon svg-icon' aria-hidden='true'>" +
            "                <use xlink:href='#iconicon-'></use>" +
            "            </svg>" +
            "            <input placeholder='请输入货物名称'/>" +
            "        </div>" +
            "    </div>",
        items: "<div class='content'></div>",
        source: [],
        afterSelect: $.noop,
    };

    $.fn.cargoSelect.Constructor = CargoSelect;

    $.fn.cargoSelect.noConflict = function () {
        $.fn.cargoSelect = old;
        return this;
    };
}));
